package org.jeecg.modules.platform.domain.task;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.jeecg.modules.platform.domain.task.impl.connection.HttpConnectionInfo;
import org.jeecg.modules.platform.domain.task.impl.connection.HttpConnectionParamInfo;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.*;

public class MapToObjectConverter {
    static ObjectMapper objectMapper = new ObjectMapper();

    /**
     *
     * @param map
     * @param clazz 目标对象 比如 User.class
     * @return
     * @param <T>
     */
    public static <T> T convertMapToObject(Map<String, Object> map, Class<T> clazz) {

        T instance;
        try {
            instance = clazz.newInstance();
            Field[] fields = getAllDeclaredFields(clazz);
            for (Field field : fields) {
                int modifiers = field.getModifiers();
                if (!Modifier.isStatic(modifiers) && !Modifier.isFinal(modifiers)) {
                    field.setAccessible(true);
                    Object value = map.get(field.getName());

                    Type type = field.getGenericType();
                    if (type  instanceof ParameterizedType){
                        Object obj = objectMapper.readValue(value.toString(),objectMapper.getTypeFactory().constructType(type));
                        field.set(instance, obj);
                    }else {
                        if (value != null) {
                            field.set(instance, value);
                        }
                    }

                }
            }
        } catch (Exception e) {
            throw new RuntimeException("Failed to convert map to object", e);
        }
        return instance;
    }

    private static Field[] getAllDeclaredFields(Class<?> clazz) {
        List<Field> fields = new ArrayList<>();
        while (clazz != null) {
            fields.addAll(Arrays.asList(clazz.getDeclaredFields()));
            clazz = clazz.getSuperclass();
        }
        return fields.toArray(new Field[0]);
    }

    public static void main(String[] args) throws JsonProcessingException {
         ObjectMapper objectMapper = new ObjectMapper();
        List<HttpConnectionParamInfo> httpConnectionParamInfoList   = new ArrayList<>();


        Map<String, Object> map = new HashMap<>();
        map.put("scheme","https");
        map.put("httpConnectionParamInfoList","[{\"receiveParamName\":2},{\"requestParamType\":2}]");


        System.out.println(MapToObjectConverter.convertMapToObject(map,HttpConnectionInfo.class));

    }

}
